﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace SQL2Entity
{
    public class SerializeUtils
    {

        /// <summary>
        /// 反序列化实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="data">实体数据</param>
        /// <returns>信息实体</returns>
        public static T Deserialize<T>(string data)
        {
            try
            {
                XmlDocument dataNode = new XmlDocument();

                dataNode.LoadXml(data);

                XmlSerializer serializer = new XmlSerializer(typeof(T));

                return (T)serializer.Deserialize(new XmlNodeReader(dataNode));
            }
            catch
            {
                throw;

                //return default(T);
            }
        }

        /// <summary>
        /// 序列化实体
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="info">信息实体</param>
        /// <returns>序列化结果</returns>
        public static string Serialize<T>(T info)
        {
            try
            {
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

                ns.Add("", "");

                XmlSerializer xs = new XmlSerializer(typeof(T));
                MemoryStream stream = new MemoryStream();
                XmlWriterSettings setting = new XmlWriterSettings();
                setting.Encoding = new UTF8Encoding(false);
                setting.Indent = true;
                using (XmlWriter writer = XmlWriter.Create(stream, setting))
                {
                    xs.Serialize(writer, info, ns);
                }
                return Encoding.UTF8.GetString(stream.ToArray());

            }
            catch
            {
                throw;
                //return string.Empty; 
            }
        }
    }
}
